package com.dnjn.mes.generator;


import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler;
import com.baomidou.mybatisplus.generator.query.SQLQuery;
import com.dnjn.mes.common.core.controller.BaseController;
import lombok.extern.slf4j.Slf4j;

import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;

/*
    数据层内容生成
 */
@Slf4j
public class MybatisPlusEntityGenerator {

    // 生成输出目录，定位到工程的java目录下
    private static String outputDir = "E:/abc-temp";
    // 生成类的作者
    private static String author = "Amber";
    // 数据源相关配置
    //
    //private static String url = "jdbc:mysql://192.168.1.221:3306/mes_device?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=UTC";
    private static String url = "jdbc:mysql://192.168.1.221:3306/mes_device?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    private static String driverName = "com.mysql.cj.jdbc.Driver";
    private static String userName = "root";
    private static String userPwd = "123456";
    // DAO的包路径
    private static String parentPackage = "com.dnjn.mes";
    public static final String modulename = "biz";
    // 待生成的表名，注意是覆盖更新
    private static String[] tableNames;

    static {
        tableNames = new String[]{
//                "mes_assembly",
//                "mes_config",
//                "mes_equipment",
//                "mes_except",
//                "mes_except_plan_xref",
//                "mes_record_beat",
//                "mes_record_capacity",
//                "mes_record_except",
//                "mes_register_address",
//                "mes_resolve_plan",
//                "mes_workpiece",
//                "mes_record_status",
//                "mes_realtime_capacity",
//                "mes_record_maintain",
//                "mes_message"
//                "mes_record_capacity"

                "mes_workforce_config",

        };
    }


    public static void main(String[] args) {
        FastAutoGenerator
                .create(url, userName, userPwd)
                .injectionConfig(builder -> {
                    builder.beforeOutputFile((tableInfo, map) -> {
                        log.info("---- tableInfo {},  objectMap {}", tableInfo.getEntityName(), map.size());
                    }).customMap(new HashMap<>());

                })

                .globalConfig(builder -> {
                    builder.disableOpenDir()
                            .author(author) // 设置作者
                            //.enableSwagger() // 开启 swagger 模式
                            //.enableSpringdoc()
                            //.fileOverride() // 覆盖已生成文件
                            .outputDir(outputDir + "/src/main/java"); // 指定输出目录
                })
                .dataSourceConfig(builder -> builder
                        .dbQuery(new MySqlQuery())
                        .typeConvert(new MySqlTypeConvert())
                        //.schema("")
                        .keyWordsHandler(new MySqlKeyWordsHandler())
                        .databaseQueryClass(SQLQuery.class)
                        .typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == Types.SMALLINT) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);

                        }))
                .packageConfig(builder -> {
                    builder.parent(parentPackage) // 设置父包名
                            .moduleName(modulename) // 设置父包模块名
                            .entity("domain")
                            .pathInfo(Collections.singletonMap(OutputFile.xml,
                                    outputDir + "/src/main/resources/mapper/" + modulename)); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder
                            .addInclude(tableNames)
                            .addTablePrefix("", "")

                            .controllerBuilder().enableFileOverride().enableRestStyle().enableHyphenStyle()

                            .superClass(BaseController.class)
                            .mapperBuilder().enableFileOverride()

                            .serviceBuilder().enableFileOverride()
                            //.formatServiceFileName("%sService")
                            //.formatServiceImplFileName("%sServiceImpl")

                            .mapperBuilder().enableFileOverride().enableBaseResultMap().enableBaseColumnList()

                            .entityBuilder().enableFileOverride().enableLombok().idType(IdType.ASSIGN_ID)

                            //.enableActiveRecord()
                            .superClass("com.dnjn.mes.common.core.domain.BaseEntity")

                            .naming(NamingStrategy.underline_to_camel)
                            .columnNaming(NamingStrategy.underline_to_camel)
                            .addSuperEntityColumns("create_by", "create_time", "update_time", "update_by", "version",
                                    "remark"/*, "deleted"*/)
                            //.enableChainModel()
                            .addTableFills(new Column("create_time", FieldFill.INSERT))
                            .addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE))
                            .versionPropertyName("version")
                            .versionColumnName("version")


                    ;
                })
                //.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .templateConfig(builder -> {
                    builder.controller("vm/mybatis-plus/controller.java")
                            .service("vm/mybatis-plus/service.java")
                            .serviceImpl("vm/mybatis-plus/serviceImpl.java")
                            .entity("vm/mybatis-plus/domain.java")
                            .xml("vm/mybatis-plus/mapper.xml")
                    ;
                })
                .execute();
//        entityGenerator();
    }


}
